import 'dart:convert';

import 'package:http/http.dart';
import 'package:time/http/response/http_list_response.dart';
import 'package:time/http/response/http_normal_response.dart';
import 'package:time/http/response/http_page_response.dart';

import 'callback/http_request_callback.dart';
import 'http_config.dart';
import 'http_log.dart';
import 'http_result_code.dart';

class HttpRequest<T> {
  /// get 请求
  Future<bool> requestGet(String unencodedPath, HttpRequestCallback<T>? callback, Map<String, String> params) async {
    addPopParamsAndToken(params);
    return quest(await get(getUri(unencodedPath, params)), callback);
  }

  /// post 请求
  Future<bool> requestPost(String unencodedPath, HttpRequestCallback<T>? callback, Map<String, String> params) async {
    addPopParamsAndToken(params);
    return quest(await post(getUri(unencodedPath), body: params), callback);
  }

  /// 统一处理url
  getUri(String unencodedPath, [Map<String, String>? params]) {
    return Uri.http(HttpConfig.BASE_URL, HttpConfig.BASE_PROJECT + unencodedPath, params);
  }

  /// 返回处理
  Future<bool> quest(Response response, HttpRequestCallback<T>? callback) async {
    HttpLog.log(response);
    //http状态码
    var statusCode = response.statusCode;
    if (statusCode == 200) {
      //数据返回码
      var jsonObject = jsonDecode(response.body);
      var resultCode = jsonObject["resultCode"];

      if (resultCode == HttpResultCode.RESULT_CODE_SUCCESS) {
        //返回成功
        if (callback != null) {
          if (callback.onSuccess != null) {
            callback.onSuccess!(HttpNormalResponse<T>.fromJson(callback.className, jsonObject).data);
          } else if (callback.onSuccessList != null) {
            callback.onSuccessList!(HttpListResponse<T>.fromJson(callback.className, jsonObject).data);
          } else if (callback.onSuccessPage != null) {
            callback.onSuccessPage!(HttpPageResponse<T>.fromJson(callback.className, jsonObject).data);
          } else {
            print("success but no callback");
          }
        }
        return true;
      } else {
        //返回失败
        if (callback != null && callback.onError != null) {
          callback.onError!(resultCode, jsonObject["msg"]);
        } else {
          print("error but no callback");
        }
        return false;
      }
    } else {
      //非200状态
      if (callback != null && callback.onError != null) {
        callback.onError!(statusCode, "数据获取异常");
      }
    }
    return false;
  }
}

/// 添加公共参数
void addPopParamsAndToken(Map<String, String> requestParams) {
  var popParams = generatePopParams();
  //添加公共参数
  requestParams.addAll(popParams);
//    //计算token
//    requestParams['token'] =
//        TokenFactory.generateToken(requestParams, ShareUtils.token);
}

/// 生成公共参数
generatePopParams() {
  Map<String, String> map = Map();
//    map['appType'] = Platform.operatingSystem;
//    map['systemVersion'] = Platform.version;
//    map['clientVersion'] = "1.0.0";
//    map['clientPackage'] = "com.xueduoduo.wande.evaluation";
//    map['deviceId'] = ShareUtils.devideId;
//    map['accessKey'] = HttpConfig.ACCESS_KEY;
//    var dateFormat = formatDate(
//        DateTime.now(), [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]);
//    map['rdmTime'] = dateFormat;
//
//    if (ShareUtils.userBean != null) {
//      map['operatorId'] = ShareUtils.userBean.userId;
//      map['schoolCode'] = ShareUtils.userBean.schoolCode;
//    }
  return map;
}
